package com.musifind.chat;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.musifind.activities.ConfirmMatchActivity;
import com.musifind.activities.R;
import com.musifind.activities.WelcomeActivity;
import com.musifind.activities.WhoIsListeningWhatActivity;

public class GCMNotificationIntentService extends IntentService {

	public static final int NOTIFICATION_ID = 1;
	private NotificationManager mNotificationManager;
	NotificationCompat.Builder builder;

	public GCMNotificationIntentService() {
		super("GcmIntentService");
	}

	public static final String TAG = "GCMNotificationIntentService";

	@Override
	protected void onHandleIntent(Intent intent) {

		Log.d(TAG, "onHandleIntent " + intent.getDataString());

		Bundle extras = intent.getExtras();
		GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

		String messageType = gcm.getMessageType(intent);

		if (extras != null) {
			if (!extras.isEmpty()) {
				if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
					sendNotification("Send error: " + extras.toString());
				} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
					sendNotification("Deleted messages on server: " + extras.toString());
				} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {

					for (int i = 0; i < 3; i++) {
						Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime());
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
						}
					}
					Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

					if (Config.ACTION_MATCH_ISTEK.equals(extras.getString(Config.ACTION))) {
						String fromRegId = extras.getString(Config.FROM_REG_ID);
						String userName = extras.getString(Config.FROM_USER_NAME);
						String trackId = extras.getString(Config.TRACK_ID);
						String trackName = extras.getString(Config.TRACK_NAME);
						String artistName = extras.getString(Config.ARTIST_NAME);
						String fromUserId = extras.getString(Config.FROM_USER_ID);
						matchIstek(fromRegId, userName, trackId, trackName, artistName, fromUserId);
					} else if (Config.ACTION_MATCH_CONFIRM.equals(extras.getString(Config.ACTION))) {
						String fromRegId = extras.getString(Config.FROM_REG_ID);
						String fromUserName = extras.getString(Config.FROM_USER_NAME);
						String tarackId = extras.getString(Config.TRACK_ID);
						String matchingId = extras.getString(Config.MATCHING_ID);
						String fromUserId = extras.getString(Config.FROM_USER_ID);
						// String trackName = extras.getString(Config.TRACK_NAME);
						// String artistName = extras.getString(Config.ARTIST_NAME);
						matchConfirm(fromRegId, fromUserName, fromUserId, tarackId, matchingId);
					} else if (Config.ACTION_MATCH_REJECT.equals(extras.getString(Config.ACTION))) {
						String fromRegId = extras.getString(Config.FROM_REG_ID);
						String userName = extras.getString(Config.FROM_USER_NAME);
						// String tarackId = extras.getString(Config.TRACK_ID);
						// String trackName = extras.getString(Config.TRACK_NAME);
						// String artistName = extras.getString(Config.ARTIST_NAME);
						matchReject(fromRegId, userName);
					} else {
						try {
							Log.d(TAG, "onHandleIntent - CHAT ");
							Intent chatIntent = new Intent("com.musifind.chat.chatmessage");
							chatIntent.putExtra("CHAT_MESSAGE", extras.get("CHAT_MESSAGE").toString());
							sendBroadcast(chatIntent);
						} catch (Exception e) {
							e.printStackTrace();
						}
						// sendNotification("MusiFind! Sender: " + extras.get(Config.REGISTER_NAME) + ". Message: "
						// + extras.get(Config.MESSAGE_KEY));
					}
				}
			}
		}
		GcmBroadcastReceiver.completeWakefulIntent(intent);
	}

	private void matchIstek(String regId, String userName, String trackId, String trackName, String artistName,
			String fromUserId) {
		mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

		String msg = "" + userName + " sizinle eşleşmek istiyor!";
		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "MusiFind";
		long when = System.currentTimeMillis();

		int requestID = (int) System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);
		Context context = getApplicationContext();
		Intent notificationIntent = new Intent(this, ConfirmMatchActivity.class);

		notificationIntent.putExtra(Config.FROM_REG_ID, regId);
		notificationIntent.putExtra(Config.FROM_USER_NAME, userName);
		notificationIntent.putExtra(Config.TRACK_ID, trackId);
		notificationIntent.putExtra(Config.TRACK_NAME, trackName);
		notificationIntent.putExtra(Config.ARTIST_NAME, artistName);
		notificationIntent.putExtra(Config.FROM_USER_ID, fromUserId);

		notificationIntent.setAction("myString" + requestID);
		PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent, 0);
		notificationIntent.setData((Uri.parse("mystring" + requestID)));
		notification.setLatestEventInfo(context, "Eşleşme Bildirimi", msg, contentIntent);
		notification.flags += Notification.FLAG_ONGOING_EVENT;
		notification.flags += Notification.FLAG_AUTO_CANCEL;
		mNotificationManager.notify(NOTIFICATION_ID, notification);
	}

	private void matchConfirm(String fromRegId, String fromUserName, String fromUserId, String trackId,
			String matchingId) {
		mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

		String msg = fromUserName + " eşleşme isteğinizi kabul etti";

		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "MusiFind ";
		long when = System.currentTimeMillis();

		int requestID = (int) System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);
		Context context = getApplicationContext();
		Intent notificationIntent = new Intent(this, ChatActivity.class);

		Log.i(TAG, "MATCHING_ID ::::::" + matchingId);

		notificationIntent.putExtra(Config.FROM_REG_ID, fromRegId);
		notificationIntent.putExtra(Config.FROM_USER_NAME, fromUserName);
		notificationIntent.putExtra(Config.FROM_USER_ID, fromUserId);
		notificationIntent.putExtra(Config.TRACK_ID, trackId);
		notificationIntent.putExtra("mId", matchingId);
		// notificationIntent.putExtra(Config.TRACK_NAME, trackName);
		// notificationIntent.putExtra(Config.ARTIST_NAME, artistName);

		notificationIntent.setAction("myString" + requestID);
		PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent, 0);
		notificationIntent.setData((Uri.parse("mystring" + requestID)));
		notification.setLatestEventInfo(context, "Eşleşme Bildirimi", msg, contentIntent);
		notification.flags += Notification.FLAG_ONGOING_EVENT;
		notification.flags += Notification.FLAG_AUTO_CANCEL;
		mNotificationManager.notify(NOTIFICATION_ID, notification);
	}

	private void matchReject(String fromRegId, String userName) {
		mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

		String msg = userName + " eşleşme isteğinizi geri çevirdi";
		int icon = R.drawable.ic_launcher;
		CharSequence tickerText = "MusiFind ";
		long when = System.currentTimeMillis();

		int requestID = (int) System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);
		Context context = getApplicationContext();
		Intent notificationIntent = new Intent(this, WhoIsListeningWhatActivity.class);

		// notificationIntent.putExtra(Config.FROM_REG_ID, fromRegId);
		// notificationIntent.putExtra(Config.FROM_USER_NAME, userName);
		// notificationIntent.putExtra(Config.TRACK_ID, trackId);
		// notificationIntent.putExtra(Config.TRACK_NAME, trackName);
		// notificationIntent.putExtra(Config.ARTIST_NAME, artistName);

		notificationIntent.setAction("myString" + requestID);
		PendingIntent contentIntent = PendingIntent.getActivity(this, requestID, notificationIntent, 0);
		notificationIntent.setData((Uri.parse("mystring" + requestID)));
		notification.setLatestEventInfo(context, "Eşleşme Bildirimi", msg, contentIntent);
		notification.flags += Notification.FLAG_ONGOING_EVENT;
		notification.flags += Notification.FLAG_AUTO_CANCEL;
		mNotificationManager.notify(NOTIFICATION_ID, notification);
	}

	// private void sendNotification(String msg) {
	// Log.d(TAG, "Preparing to send notification...: " + msg);
	// mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
	//
	// PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this,
	// WhoIsListeningWhatActivity.class), 0);
	//
	// NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(
	// "Musifind Bildirim").setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setContentText(msg);
	//
	// mBuilder.setContentIntent(contentIntent);
	// mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
	// Log.d(TAG, "Notification sent successfully.");
	// }

	private void sendNotification(String msg) {
		Log.d(TAG, "Preparing to send notification...: " + msg);
		mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, WelcomeActivity.class), 0);

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle("GCM XMPP Message").setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
				.setContentText(msg);

		mBuilder.setContentIntent(contentIntent);
		mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
		Log.d(TAG, "Notification sent successfully.");
	}
}
